package com.gavin.demo4fresco.adapters;

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.gavin.demo4fresco.R;
import com.gavin.demo4fresco.model.entities.PictureObj;

import java.util.List;

/**
 * Created by Gavin on 16/2/17.
 */
public class ThumbnailAdapter extends RecyclerView.Adapter<ThumbnailAdapter.ThumbnailViewHolder> {
    private Context mContext;
    private List<PictureObj> objs;

    public ThumbnailAdapter(Context context, List<PictureObj> objs) {
        mContext = context;
        this.objs = objs;
    }

    @Override
    public ThumbnailViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ThumbnailViewHolder holder = new ThumbnailViewHolder(LayoutInflater.from(mContext).inflate(R.layout.main_item_content_recycleview, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(ThumbnailViewHolder holder, int position) {
        GenericDraweeHierarchy hierarchy = holder.draweeView.getHierarchy();
        hierarchy.setProgressBarImage(new ProgressBarDrawable());
        /**
         * 如果本地JPEG图，有EXIF的缩略图，image pipeline 可以立刻返回它作为一个缩略图。
         * Drawee 会先显示缩略图，完整的清晰大图在 decode 完之后再显示
         */
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(objs.get(position).getUrl()))
                .setLocalThumbnailPreviewsEnabled(true)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setOldController(holder.draweeView.getController())
                .build();
        holder.draweeView.setController(controller);
        holder.mTextView.setText(objs.get(position).getDesc());
    }

    @Override
    public int getItemCount() {
        return objs.size();
    }

    class ThumbnailViewHolder extends RecyclerView.ViewHolder {
        SimpleDraweeView draweeView;
        TextView mTextView;

        public ThumbnailViewHolder(View itemView) {
            super(itemView);
            draweeView = (SimpleDraweeView) itemView.findViewById(R.id.main_item_content_draweeview);
            mTextView = (TextView) itemView.findViewById(R.id.main_item_content_textview);
        }
    }
}
